package com.ruoyi.web.ydz.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.web.ydz.domain.MedicationReminder;
import com.ruoyi.web.ydz.mapper.MedicationReminderMapper;
import com.ruoyi.web.ydz.service.IMedicationReminderService;
import com.ruoyi.web.ydz.util.messageUtil.SendSms;
import com.ruoyi.web.ydz.util.quartz.QuartServiceImpl;
import com.ruoyi.web.ydz.util.quartz.quartzUtil;
import org.quartz.JobDataMap;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 用药提醒功能Service业务层处理
 *
 * @author DRX
 * @date 2024-10-15
 */
@Service
public class MedicationReminderServiceImpl implements IMedicationReminderService {
    @Resource
    private MedicationReminderMapper medicationReminderMapper;

    @Resource
    private SendSms sendSms;

    @Resource
    private QuartServiceImpl quartService;

    /**
     * 查询用药提醒功能
     *
     * @param id 用药提醒功能主键
     * @return 用药提醒功能
     */
    @Override
    public MedicationReminder selectMedicationReminderById(Long id) {
        MedicationReminder medicationReminder = medicationReminderMapper.selectMedicationReminderById(id);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!Objects.isNull(medicationReminder) && !Objects.isNull(medicationReminder.getCreateBy())) {
            if (user.getUserId() != Long.parseLong(medicationReminder.getCreateBy())) {
                return null;
            }
        } else {
            return null;
        }
        return medicationReminder;
    }

    /**
     * 查询用药提醒功能列表
     *
     * @param medicationReminder 用药提醒功能
     * @return 用药提醒功能
     */
    @Override
    public List<MedicationReminder> selectMedicationReminderList(MedicationReminder medicationReminder) {

        /*
         * 如果当前用户身份不是管理员
         * 则查询自身的用药提醒
         * */
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        if (!Objects.isNull(roles)) {
            roles.forEach(bean -> {
                if (100l == bean.getRoleId().longValue()) {
                    medicationReminder.setCreateBy(String.valueOf(user.getUserId()));
                }
            });
        } else {
            medicationReminder.setCreateBy(String.valueOf(user.getUserId()));
        }

        return medicationReminderMapper.selectMedicationReminderList(medicationReminder);
    }

    /**
     * 新增用药提醒功能
     *
     * @param medicationReminder 用药提醒功能
     * @return 结果
     */
    @Override
    public int insertMedicationReminder(MedicationReminder medicationReminder) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        medicationReminder.setCreateBy(String.valueOf(user.getUserId()));
        medicationReminder.setCreateName(user.getNickName());
        medicationReminder.setCreateTime(DateUtils.getNowDate());

        int i = medicationReminderMapper.insertMedicationReminder(medicationReminder);

        /*如果用户选择了提醒时间*/
        if (!Objects.isNull(medicationReminder.getRemindTime())) {
            Long dateDifference = sendSms.getDateDifference(medicationReminder.getRemindTime());

            /*如果用户传入时间小于当前时间 则进行提醒*/
            if (i > 0 && dateDifference >= 0) {

                /*quartz*/
                JobDataMap jobDataMap = new JobDataMap();
                jobDataMap.put("medicationReminderId", medicationReminder.getId());
                R r = quartService.addCronJob("jobname" + medicationReminder.getId(), quartzUtil.dateToCron(medicationReminder.getRemindTime()), "com.ruoyi.web.ydz.util.quartz.TaskJob", "triggername" + medicationReminder.getId(), jobDataMap);

                /*MQ*/
                /*rabbitTemplate.convertAndSend(delayedConfig.EXCHANGE, delayedConfig.KEY, JSONUtil.toJsonStr(medicationReminder), message -> {
                    message.getMessageProperties().setDelay(1000 * dateDifference.intValue());
                    return message;
                });*/

            }
        }

        return i;
    }

    /**
     * 修改用药提醒功能
     *
     * @param medicationReminder 用药提醒功能
     * @return 结果
     */
    @Override
    public AjaxResult updateMedicationReminder(MedicationReminder medicationReminder) {

        AjaxResult ajaxResult = new AjaxResult();
        SysUser user = SecurityUtils.getLoginUser().getUser();

        if (!Objects.isNull(medicationReminder.getCreateBy()) && Long.parseLong(medicationReminder.getCreateBy()) == user.getUserId().longValue()) {
            MedicationReminder mrdata = medicationReminderMapper.selectMedicationReminderById(medicationReminder.getId());

            medicationReminder.setUpdateBy(String.valueOf(user.getUserId()));
            medicationReminder.setUpdateName(user.getNickName());
            medicationReminder.setUpdateTime(DateUtils.getNowDate());
            int i = medicationReminderMapper.updateMedicationReminder(medicationReminder);

            Long dateDifference = sendSms.getDateDifference(medicationReminder.getRemindTime());

            if ("0".equals(medicationReminder.getState()) && "1".equals(mrdata.getState())) {
                /*如果当前 提醒修由打开 改为 关闭
                 * 将删除定时任务*/
                R r = quartService.deleteCronJob("jobname" + medicationReminder.getId(), "default_job_group", "triggername" + medicationReminder.getId(), "default_trigger_group");
                ajaxResult.put("code", 200);
                ajaxResult.put("msg", "修改成功");
                System.out.println("删除");
                return ajaxResult;
            } else if ("0".equals(medicationReminder.getState()) && "0".equals(mrdata.getState())) {
                /*如果当前 提醒修由关闭 改为 关闭
                 * 则不修改
                 * */
                ajaxResult.put("code", 200);
                ajaxResult.put("msg", "修改成功");
                return ajaxResult;
            } else if ("1".equals(medicationReminder.getState()) && "0".equals(mrdata.getState())) {
                /*如果当前 提醒修由关闭 改为 打开
                 * 意味 当前提醒已经没有定时任务
                 * 需新加任务
                 * */
                JobDataMap jobDataMap = new JobDataMap();
                jobDataMap.put("medicationReminderId", medicationReminder.getId());
                if (dateDifference > 0) {
                    R r = quartService.addCronJob("jobname" + medicationReminder.getId(), quartzUtil.dateToCron(medicationReminder.getRemindTime()), "com.ruoyi.web.ydz.util.quartz.TaskJob", "triggername" + medicationReminder.getId(), jobDataMap);
                }
                ajaxResult.put("code", 200);
                ajaxResult.put("msg", "修改成功");
                return ajaxResult;
            }

            /* 如果当前 提醒修由打开 改为 打开
             * 并且提醒时间被修改
             * 需判断 修改的时候是否大于当前时间
             * 且 如果当前提醒已经触发过 则 需要新增任务 否则 直接修改
             * */
            if (mrdata.getRemindTime().getTime() != medicationReminder.getRemindTime().getTime()) {
                if (i > 0 && dateDifference > 0) {

                    /*MQ*/
                    /*rabbitTemplate.convertAndSend(delayedConfig.EXCHANGE, delayedConfig.KEY, JSONUtil.toJsonStr(medicationReminder), message -> {
                        message.getMessageProperties().setDelay(1000 * dateDifference.intValue());
                        return message;
                    });*/

                    /*quartz*/
                    /*如果当前提醒已经触发过 将新增 否则将修改*/
                    if (mrdata.getRemindTime().before(new Date())) {
                        JobDataMap jobDataMap = new JobDataMap();
                        jobDataMap.put("medicationReminderId", medicationReminder.getId());
                        R r = quartService.addCronJob("jobname" + medicationReminder.getId(), quartzUtil.dateToCron(medicationReminder.getRemindTime()), "com.ruoyi.web.ydz.util.quartz.TaskJob", "triggername" + medicationReminder.getId(), jobDataMap);
                    } else {
                        R r = quartService.updateCronJob("jobname" + medicationReminder.getId(), quartzUtil.dateToCron(medicationReminder.getRemindTime()), "triggername" + medicationReminder.getId());
                    }

                }
            }

            ajaxResult.put("code", 200);
            ajaxResult.put("msg", "修改成功");
        } else {
            ajaxResult.put("code", 200);
            ajaxResult.put("msg", "修改失败,请确认提醒所属人");
        }

        return ajaxResult;
    }

    /**
     * 批量删除用药提醒功能
     *
     * @param ids 需要删除的用药提醒功能主键
     * @return 结果
     */
    @Override
    public int deleteMedicationReminderByIds(Long[] ids) {
        int i = medicationReminderMapper.deleteMedicationReminderByIds(ids);
        for (int x = 0; x < ids.length; x++) {
            R r = quartService.deleteCronJob("jobname" + ids[x], "default_job_group", "triggername" + ids[x], "default_trigger_group");
        }
        return i;
    }

    /**
     * 删除用药提醒功能信息
     *
     * @param id 用药提醒功能主键
     * @return 结果
     */
    @Override
    public int deleteMedicationReminderById(Long id) {
        int i = medicationReminderMapper.deleteMedicationReminderById(id);
        R r = quartService.deleteCronJob("jobname" + id, "default_job_group", "triggername" + id, "default_trigger_group");
        return i;
    }

    @Override
    public List<MedicationReminder> getRestoreMedicationReminder(){
        return medicationReminderMapper.getRestoreMedicationReminder();
    }

}
